import datetime

import jwt
from rest_framework.authentication import BaseAuthentication

from django_erp.settings import SECRET_KEY


def create_token(payload, timeout=10):
    payload["exp"] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
    headers = {
        'alg': "HS256",
        'typ': "jwt"
    }
    result = jwt.encode(headers=headers, payload=payload, key=SECRET_KEY, algorithm="HS256")
    return result


def get_payload(token):
    result = {
        "status": False,
        "data": None,
        "error": None
    }
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms="HS256")
        result["status"] = True
        result["data"] = payload
    except jwt.exceptions.ExpiredSignatureError:
        result["error"] = "token已经失效了"
    except jwt.exceptions.DecodeError:
        result["error"] = "token认证失败了"
    except jwt.exceptions.InvalidTokenError:
        result["error"] = "无效的、非法的token"
    return result


# 用户在Url中进行token的参数配置
class JwtQueryParamAuthentication(BaseAuthentication):
    # 复写方法
    def authenticate(self, request):
        # 从url中拿到token
        token = request.GET.get("token")
        result_payload = get_payload(token)
        # print(result_payload)
        return result_payload, token


class JwtHeaderAuthentication(BaseAuthentication):
    # 复写方法
    def authenticate(self, request):
        # 从url中拿到token
        token = request.META.get("HTTP_TOKEN")
        # print(token)
        result_payload = get_payload(token)
        # print(result_payload)
        return result_payload, token